package com.example.yichuangyun.utils;

import static android.os.Environment.DIRECTORY_PICTURES;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.FileUtils;
import android.provider.MediaStore;
import android.webkit.MimeTypeMap;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

public class FileUtil {

    public static List<File> searchFiles(File folder) {
        List<File> result = new ArrayList<>();
        if (folder.isFile())
            result.add(folder);
        File[] subFolders = folder.listFiles(file -> {
            if (file.isDirectory() && checkFileName(file.getName())) {
                return true;
            }
            return checkFileNameEnd(file.getName());
        });
        if (subFolders != null) {
            for (File file : subFolders) {
                if (file.isFile()) {
                    // 如果是文件则将文件添加到结果列表中
                    result.add(file);
                } else {
                    // 如果是文件夹，则递归调用本方法，然后把所有的文件加到结果列表中
                    result.addAll(searchFiles(file));
                }
            }
        }
        return result;
    }

    //匹配目录规则
    public static boolean checkFileName(String name) {
        String[] rule = FileUtil.getFileNameRule().split(",");
        for (String string : rule) {
            if (name.toUpperCase().contains(string)) {
                return true;
            }
        }
        return false;
    }

    //匹配后缀规则
    public static boolean checkFileNameEnd(String name) {
        String[] rule = FileUtil.getFileNameEndRule().split(",");
        for (String string : rule) {
            if (name.toLowerCase().contains(string)) {
                return true;
            }
        }
        return false;
    }

    public static String getFileNameRule() {
        return "RECORD,SOUND";
    }

    public static String getFileNameEndRule() {
        return ".amr,.awb,.wav,.aac,.mp3,.m4a";
    }

    public static File getFile() {
        File parent = Environment.getExternalStorageDirectory();
        File child = null;
        String brand = Build.BRAND.toUpperCase();//获取手机厂商转大写
        switch (brand) {
            case "HUAWEI":
            case "HONOR":
                child = new File(parent, "Sounds/CallRecord");
                break;
            case "XIAOMI":
            case "REDMI":
                child = new File(parent, "MIUI/sound_recorder/call_rec");
                break;
            case "VIVO":
                child = new File(parent, "Record");
                break;
            case "OPPO":
                child = new File(parent, "Music/Recordings/Call Recordings");
                break;
            case "MEIZU":
                child = new File(parent, "Recorder");
                break;
            case "SAMSUNG":
                child = new File(parent, "Sounds");
                break;
            default:
                child = new File(parent, "");
        }
        return child;
    }

    /**
     * 获取音频文件的总时长大小
     *
     * @param filePath 音频文件路径
     * @return 返回时长大小
     */
    public static long getAudioFileVoiceTime(String filePath) {
        long mediaPlayerDuration = 0L;
        if (filePath == null || filePath.isEmpty()) {
            return 0;
        }
        MediaPlayer mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(filePath);
            mediaPlayer.prepare();
            mediaPlayerDuration = mediaPlayer.getDuration();
        } catch (IOException ioException) {

        }
        mediaPlayer.stop();
        mediaPlayer.reset();
        mediaPlayer.release();
        return mediaPlayerDuration;
    }

    public static boolean isFolderExists(String strFolder) {
        File file = new File(strFolder);
        return file.exists();
    }

//    public static File caseToMp3(MultipartFile file) {
//        String fileName = file.getOriginalFilename();
//        if (StringUtils.isNotBlank(fileName) && fileName.indexOf(".") > 0) {
//            fileName = fileName.substring(0, fileName.lastIndexOf("."));
//        }
//        //File target = new File("D:\\Users\\Uploadfile\\"+fileName+".mp3");
//        File target = new File("//root/Uploadfile/" + fileName + ".mp3");
//        try {
//            //Audio Attributes
//            AudioAttributes audio = new AudioAttributes();
//            audio.setCodec("libmp3lame");//转码器名称
//            audio.setBitRate(128000);//音频流的比特率值
//            audio.setChannels(2);//声道
//            audio.setSamplingRate(44100);//音频流的采样率
//            //Encoding attributes
//            EncodingAttributes attrs = new EncodingAttributes();
//            attrs.setFormat("mp3");//编码格式
//            attrs.setAudioAttributes(audio);
//            //Encode
//            Encoder encoder = new Encoder();
//            encoder.encode(new MultimediaObject(multipartFileToFile(file)), target, attrs);
//            System.out.println("success");
//            return target;
//        } catch (Exception ex) {
//            ex.printStackTrace();
//
//        }
//        return null;
//    }

    /**
     * 获取目录下所有文件(按时间排序)
     *
     * @param path
     * @return
     */
    public static List<File> listFileSortByModifyTime(String path) {
        List<File> list = getFiles(path, new ArrayList<>());
        if (list.size() > 0) {
            Collections.sort(list, (file, newFile) -> {
                if (file.lastModified() < newFile.lastModified()) {
                    return -1;
                } else if (file.lastModified() == newFile.lastModified()) {
                    return 0;
                } else {
                    return 1;
                }
            });
        }
        return list;
    }

    /**
     * 获取目录下所有文件
     *
     * @param realPath
     * @param files
     * @return
     */
    public static List<File> getFiles(String realPath, List<File> files) {
        File realFile = new File(realPath);
        if (realFile.isDirectory()) {
            File[] subFiles = realFile.listFiles();
            if (null != subFiles) {
                for (File file : subFiles) {
                    if (file.isDirectory()) {
                        getFiles(file.getAbsolutePath(), files);
                    } else {
                        files.add(file);
                    }
                }
            }
        }
        return files;
    }

    public static Uri uri;

    public static File createImageFile(Context context, boolean isCrop) {
        try {
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            String fileName = "";
            if (isCrop) {
                fileName = "IMG_" + timeStamp + "_CROP.jpg";
            } else {
                fileName = "IMG_" + timeStamp + ".jpg";
            }
            File rootFile = new File(context.getExternalFilesDir(null).getAbsoluteFile() + File.separator + "capture");
            if (!rootFile.exists()) {
                rootFile.mkdirs();
            }
            File imgFile;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                imgFile = new File(Environment.getExternalStoragePublicDirectory(DIRECTORY_PICTURES) + File.separator + fileName);
                // 通过 MediaStore API 插入file 为了拿到系统裁剪要保存到的uri（因为App没有权限不能访问公共存储空间，需要通过 MediaStore API来操作）
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, imgFile.getAbsolutePath());
                values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
                values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
                uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                imgFile = new File(rootFile.getAbsolutePath() + File.separator + fileName);
            }
            return imgFile;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static File getFileByUri(Uri uri, Context context) {
        File file = null;
        if (uri == null) return null;
        //android10以上转换
        if (uri.getScheme().equals(ContentResolver.SCHEME_FILE)) {
            file = new File(uri.getPath());
        } else if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
            //把文件复制到沙盒目录
            ContentResolver contentResolver = context.getContentResolver();
            String displayName = System.currentTimeMillis() + Math.round((Math.random() + 1) * 1000)
                    + "." + MimeTypeMap.getSingleton().getExtensionFromMimeType(contentResolver.getType(uri));

            try {
                InputStream is = contentResolver.openInputStream(uri);
                File cache = new File(context.getCacheDir().getAbsolutePath(), displayName);
                FileOutputStream fos = new FileOutputStream(cache);
                FileUtils.copy(is, fos);
                file = cache;
                fos.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    /**
     * 获取指定文件大小
     */
    public static String getFileSize(File file) throws Exception {
        long size = 0;
        if (file.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            size = fis.available() / 1000;
        } else {
            file.createNewFile();
        }
        return size + "k";
    }
}
